<template>
    <div class="custom-table">
        <div class="table-box">
            <el-table
                :data="getData"
                :border="border"
                :stripe="stripe"
                :style="{ width: '100%' }"
                :height="height ||'100%'"
                v-loading="loading"
                @cell-click="tableCellClick"
                @row-click="tableRowClick"
            >
                <template v-for="column in columns" :key="column.prop">
                    <el-table-column
                        :prop="column.prop"
                        :label="column.label"
                        :width="column.width || 'auto'"
                        :align="column.align || 'center'"
                    >
                        <template v-if="column.slot" #default="scope">
                            <slot
                                :name="column.slot"
                                :row="scope.row"
                                :column="scope.column"
                            />
                        </template>
                        <template v-else #default="scope">
                            {{ scope.row[column.prop] }}
                        </template>
                    </el-table-column>
                </template>
            </el-table>
        </div>
        <div class="basic-pagination">
            <div class="click" @click="goFirst">首页</div>
            <el-pagination
                v-model:current-page="basicPagination.currentPage"
                :page-size="basicPagination.pageSize"
                :size="basicPagination.size"
                :pager-count="4"
                prev-text="上一页"
                next-text="下一页"
                @prev-click="prevClick"
                @next-click="nextClick"
                layout="prev, pager, next"
                :total="basicPagination.total"
                @change="handleChange"
            />
            <div class="click" @click="goLast">尾页</div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
const props = defineProps({
    // 表头
    columns: {
        type: Array,
        required: true
    },
    // 表格数据
    data: {
        type: Array,
        default: ()=>[]
    },
    // 表格高度
    height:{
        type: String
    },
    // loading
    loading: {
        type: Boolean,
        default: false
    },
    // 边框
    border: {
        type: Boolean,
        default: false
    },
    // 斑马纹
    stripe: {
        type: Boolean,
        default: true
    },
    pagination: {
        type: Object,
        default: () => ({
            currentPage: 1,
            total: 0,
            pageSize: 5,
            size: 'default'
        })
    },
    api: {
        type: Function,
        required: false // 确保父组件传入 API 方法
    },
    // 额外参数
    searchInfo: {
        type: Object,
        default: ()=>{}
    }
});

const basicPagination = ref({
    currentPage: props.pagination.currentPage || 1,
    total: props.pagination.total || 0,
    pageSize: props.pagination.pageSize || 10,
    size: props.pagination.size || 'default'
})
const emit = defineEmits<{
    (
        event: 'handleSizeAndCurrentChange',
        pagination: { current: number; size: number }
    ): void;
    (
        event: 'cellClick',
        data: { row: Record<string, any>, column: Record<string, any> }
    ): void;
    (
        event: 'rowClick',
        data: { row: Record<string, any>, column: Record<string, any> }
    ): void;
}>();
//const emit = defineEmits(['handleSizeAndCurrentChange','tableClick'])
const handleChange = (pagination: { current: number; size: number }) => {
    emit('handleSizeAndCurrentChange', pagination);
    console.log('current-change', pagination);

    loadData();
};
const getData = computed(() => {
    return props.api ? tableData : props.data
})
const totalPages = computed(() => {
    return Math.ceil(
        basicPagination.value.total / basicPagination.value.pageSize
    );
})
const size = 'default'; // 分页器的尺寸

// 跳转到首页
const goFirst = () => {
    basicPagination.value.currentPage = 1;
    loadData();
};

// 跳转到尾页
const goLast = () => {
    basicPagination.value.currentPage = totalPages;
    loadData();
};
const prevClick = (value: number) => {
    console.log('点击上一页', value);
    if (value === 1) return
    basicPagination.value.currentPage = value - 1;
    loadData();
}
const nextClick = (value: number) => {
    console.log('点击下一页', value);
    if (value === totalPages as unknown as number) return
    basicPagination.value.currentPage = value + 1;
    loadData();
}
const loading = ref(false)
const tableData = ref([])
// 加载数据方法
const loadData = async () => {
    if (!props.api) return; // 如果是本地分页，跳过加载数据
    try {
        loading.value = true;
        const { currentPage, pageSize } = basicPagination.value;
        // 调用传入的 API 方法
        const response = await props.api({
            page: currentPage,
            size: pageSize,
            ...props.searchInfo
        });
        // 假设 API 返回 { data: [], total: 0 }
        tableData.value = response.data || [];
        basicPagination.value.total = response.total || 0;
    } catch (error) {
        console.error('加载数据失败:', error);
    } finally {
        loading.value = false;
    }
};
// 更新总数
watch(
    () => props.data,
    () => {
        if (!props.api) {
            basicPagination.value.total = props.data.length;
        }
    },
    { immediate: true }
);
// 分页变化时加载数据
watch(
    () => basicPagination.value.currentPage,
    () => {
        loadData();
    }
);

watch(
    () => basicPagination.value.pageSize,
    () => {
        loadData();
    }
);
// 初始化加载数据
onMounted(() => {
    if(props.api) {
        loadData();
    } else {
        basicPagination.value.total = props.data.length;
    }
});
/**
 * 表格cell 点击事件
 */

const tableCellClick = (row: Record<string, any>, column: Record<string, any>, cell: HTMLTableCellElement, event: Event)=>{
    emit('cellClick', { row, column })
}
/**
 * 表格row点击事件
 */
const tableRowClick = (row: Record<string, any>, column: Record<string, any>, event: Event)=>{
    emit('rowClick', { row, column })
}
</script>

<style scoped lang="less">
:deep( .el-table__header){
  width: 100% !important;
}
.custom-table {
    width: 100%;
    height: 100%;
    overflow: hidden;
        .table-box {
            height: calc(100% - 52px);
            width: 100%;
        }
}

.basic-pagination {
    font-family: '黑体';
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;

    .click {
        padding: 0 10px;
        width: auto;
        text-align: center;
        font-size: 14px;
        height: 28px !important;
        line-height: 26px !important;
        font-weight: 700;
        color: #35a8e5 !important;
        border: 2px solid #1a3d6d !important;
        box-sizing: border-box;
        cursor: pointer;
        background-color: transparent;
    }

    :deep( .el-pagination) {
        flex: 1;
        display: flex;
        justify-content: space-between;
        margin: 0 4px;
        .btn-prev,
        .btn-next {
            padding: 0 10px;
            width: auto;
            text-align: center;
            font-size: 14px;
            height: 28px !important;
            line-height: 26px !important;
            font-weight: 700;
            color: #35a8e5 !important;
            border: 2px solid #1a3d6d !important;
            box-sizing: border-box;
            cursor: pointer;
            background-color: transparent;
        }

        font-family: '黑体';
        background-color: transparent;


        .el-pager {
            li {
                min-width: 31px;
                background-color: hsla(0, 0%, 100%, 0) !important;
                padding: 0 4px;
                color: #fff;
                font-size: 13px;
                min-width: 35.5px;
                height: 28px;
                line-height: 28px;
                box-sizing: border-box;
                text-align: center;
            }

            .is-active {
                color: #409eff;
                cursor: default;
            }
        }
    }
}

:deep( .el-table) {
    background: transparent !important;
    font-family: '黑体';
    --el-table-border-color: transparent !important;
    --el-table-border: 'none' !important;

    &::before {
        z-index: inherit;
    }

    tr {
        background-color: rgba(255, 255, 255, 0) !important;
    }

    thead {
        background: url(/src/assets/img/tabTitle.png) no-repeat 50%;
        background-size: 100% 98%;

        tr th {
            background: transparent !important;
        }
    }

    .el-table__cell {
        padding: 0;
        border: none;
    }

    .el-table__row:hover>td {
        background-color: transparent !important;
    }

    .el-table__row--striped:hover {
        .el-table__cell {
            background-color: rgba(40, 85, 138, .2) !important;
        }
    }

    .el-table__row--striped {
        .el-table__cell {
            background-color: rgba(40, 85, 138, .2) !important;
        }
    }

    .cell {
        color: #c8deff;
        font-family: NotoSansCJKsc-Regular;
        line-height: 36px;
        font-size: 14px;
        white-space: nowrap;
    }

}
</style>
